<template>
  <div class="page-header">
    <el-page-header @back="goBack" :icon="ArrowLeftBold">
      <template #content>
        <span v-if="flag =='admin'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<el-icon><User /></el-icon>信息管理</span>
        <span v-if="flag !='admin'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<el-icon><User /></el-icon>个人中心</span>
      </template>
    </el-page-header>
  </div>
  <el-tabs tab-position="left" style="margin-top: 10px">
    <el-tab-pane>
      <template #label>
        <span class="custom-tabs-label">
          <el-icon><UserFilled /></el-icon>
          <span>账号信息</span>
        </span>
      </template>
      <el-card style="min-height: 680px;">
          <div class="all-search">
            <el-button type="primary" :icon="Edit" size="mini"  @click="onEdit" round>
              编辑
            </el-button>
            <el-button type="success" :icon="Finished" size="mini" class="btn-background-color-reset" @click="onFinished" round>保存
            </el-button>
          </div>
        <div>
        <img :src="userInfo.userAvatar" alt="" class="avatar" />
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8888/api/file/upload"
              :data="{ type: 'user', id: userId }"
              :headers="{ token : UserStore.token  }"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <el-button :icon="PictureFilled" style="margin-left: 200px;margin-bottom: 10px;" v-if="true" type="info" round @click="">更换头像</el-button>
          </el-upload>
        </div>
        <el-form class="search-form" style="margin-top: 20px">
          <el-form-item label-width="100px" label="用户账号:" size="default">
            <el-input v-if="editFlag" v-model="userInfo.userId" placeholder="请输入您的账号" clearable></el-input>
            <span v-if="!editFlag">{{userInfo.userId}}</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="用户昵称:" size="default">
            <el-input v-if="editFlag" v-model="userInfo.userName" placeholder="请输入您的昵称" clearable></el-input>
            <span v-if="!editFlag">{{userInfo.userName}}</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="姓名:" size="default">
            <el-input v-if="editFlag" v-model="userInfo.realName" placeholder="请输入姓名" clearable></el-input>
            <span v-if="!editFlag">{{userInfo.realName}}</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="性别:" size="default">
            <el-select v-if="editFlag" style="width: 100%" v-model="userInfo.gender" placeholder="请选择性别" clearable>
              <el-option label="男" value=1></el-option>
              <el-option label="女" value=0></el-option>
            </el-select>
            <span v-if="!editFlag && userInfo.gender == 1">男</span>
            <span v-if="!editFlag && userInfo.gender != 1">女</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="证件类型:" size="default">
            <el-select v-if="editFlag" style="width: 100%" v-model="userInfo.identityCardType" placeholder="请选择您的证件类型" clearable>
              <el-option label="身份证" value=1></el-option>
              <el-option label="军官证" value=2></el-option>
              <el-option label="护照" value=3></el-option>
            </el-select>
            <span v-if="!editFlag && userInfo.identityCardType == 1">身份证</span>
            <span v-if="!editFlag && userInfo.identityCardType == 2">军官证</span>
            <span v-if="!editFlag && userInfo.identityCardType == 3">护照</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="用户邮箱:" size="default">
            <el-input v-if="editFlag" v-model="userInfo.email" placeholder="请输入您的邮箱号" clearable></el-input>
            <span v-if="!editFlag">{{userInfo.email}}</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="手机号:" size="default">
            <el-input v-if="editFlag" v-model="userInfo.phone" placeholder="请输入手机号" clearable></el-input>
            <span v-if="!editFlag">{{userInfo.phone}}</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="您的积分:" size="default">
            <span style="color: #29958d;">{{userInfo.userPoint}}</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="您的余额:" size="default">
            <span style="color: #29958d;">{{userInfo.userMoney}}元</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="您的会员级别:" size="default">
            <span v-if="userInfo.userLevel == 1" style="color: #29958d;">普通会员</span>
            <span v-if="userInfo.userLevel == 2" style="color: #29958d;">青铜</span>
            <span v-if="userInfo.userLevel == 3" style="color: #29958d;">白银</span>
            <span v-if="userInfo.userLevel == 4" style="color: #29958d;">黄金</span>
            <span v-if="userInfo.userLevel == 5" style="color: #29958d;">钻石</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="注册时间:" size="default">
            <span style="color: #29958d;">{{userInfo.createTime}}</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="更新时间:" size="default">
            <span style="color: #29958d;">{{userInfo.updateTime}}</span>
          </el-form-item>
          <el-form-item label-width="100px"  label="用户简介:" size="default">
            <el-input v-if="editFlag" v-model="userInfo.userProfile" type="textarea"></el-input>
            <span v-if="!editFlag">{{userInfo.userProfile}}</span>
          </el-form-item>
        </el-form>
      </el-card>
    </el-tab-pane>
    <el-tab-pane>
      <template #label>
        <span class="custom-tabs-label">
          <el-icon><Key /></el-icon>
          <span>安全信息</span>
        </span>
      </template>
      <el-card style="min-height: 680px;">
        <span>更换密码</span>
        <el-form  style="margin-top: 20px">
          <el-form-item label-width="100px" label="老密码:" size="default">
            <el-input    type="password"
                         show-password
                         v-model="oldPassword"
                         size="large"
                         placeholder="请输入您的老密码"
                         clearable></el-input>
          </el-form-item>
          <el-form-item label-width="100px"  label="新密码:" size="default">
            <el-input   type="password"
                        show-password
                        v-model="newPassword"
                        size="large"
                        placeholder="请输入您的新密码"
                        clearable></el-input>
          </el-form-item>
        </el-form>
        <div>
        <el-button
            style="align-content: center"
            type="primary"
            size="default"
            @click="updatePassword"
        >确认更改
        </el-button>
        </div>
      </el-card>
    </el-tab-pane>
    <el-tab-pane>
      <template #label>
        <span class="custom-tabs-label">
          <el-icon><LocationFilled /></el-icon>
          <span>地址管理</span>
        </span>
      </template>
      <el-card style="min-height: 680px;">
        <div class="all-add">
          <el-button round type="success" size="mini" class="btn-background-color-add" @click="addAddressDialog">
            新增
          </el-button>
        </div>
        <el-table :row-style="{height: '30px'}" :data="userAdressList"
                  :cell-style="{ textAlign: 'center' }"
                  :header-cell-style="{textAlign: 'center',background:'#d1c9c9'}" border
                  style="width: 100%" size="small" max-height="400 ">
          <el-table-column prop="id" label="地址ID" min-width="50" show-overflow-tooltip="true"/>
          <el-table-column prop="isDefault" label="是否默认" min-width="40" show-overflow-tooltip="true">
            <template #default="scope">
              <el-tooltip effect="dark" :content="'默认'" placement="top">
                <el-icon color="#68f703"  v-if="scope.row.isDefault == 1 " :size="15">
                  <SuccessFilled/>
                </el-icon>
              </el-tooltip>
              <el-tooltip effect="dark" :content="'非默认'" placement="top">
                <el-icon color="#f87103"  v-if="scope.row.isDefault != 1 " :size="15">
                  <WarningFilled/>
                </el-icon>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="zip" label="邮政编码" min-width="80" show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="province" label="省" min-width="60" show-overflow-tooltip="true"/>
          <el-table-column prop="city" label="市" min-width="60" show-overflow-tooltip="true"/>
          <el-table-column prop="district" label="县" min-width="60" show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="address" label="详细地址" min-width="200" show-overflow-tooltip="true"/>
          <el-table-column prop="createTime" label="创建时间" min-width="100" show-overflow-tooltip="true"/>
          <el-table-column prop="updateTime" label="更新时间" min-width="100" show-overflow-tooltip="true"/>
          <el-table-column fixed="right" label="操作" width="90">
            <template #default="scope">
              <el-button  link type="primary" class="btn-background-color-xiangqing" size="small"
                          @click.stop="UpdateAddressDialog(scope.row)">更改
              </el-button>
              <el-button  link type="primary" class="btn-background-color-red" size="small"
                          @click.stop="removeAdressDialog(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-tab-pane>
  </el-tabs>
  <el-dialog   v-model="AddIsShowDialog" title="Warning" width="30%" align-center draggable destroy-on-close>
    <template #header>
      <h1>新增地址</h1>
    </template>
    <el-form :model="AddressForm">
      <el-form-item label="省" prop="province">
        <el-input
            v-model="AddressForm.province"
            clearable
            placeholder="省"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="市" prop="city">
        <el-input
            v-model="AddressForm.city"
            clearable
            placeholder="市"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="区" prop="district">
        <el-input
            v-model="AddressForm.district"
            clearable
            placeholder="县、区"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮政编码" prop="zip">
        <el-input
            v-model="AddressForm.zip"
            clearable
            placeholder="邮政编码"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input
            v-model="AddressForm.address"
            clearable
            placeholder="详细地址"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="类型">
        <el-radio-group v-model="AddressForm.isDefault">
          <el-radio label="1">默认</el-radio>
          <el-radio label="0">不默认</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button color="red" type="primary" @click="Addsubmit">确认</el-button>
        <el-button @click="Addclose">取消</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog   v-model="UpdateIsShowDialog" title="Warning" width="30%" align-center draggable destroy-on-close>
    <template #header>
      <h1>新增地址</h1>
    </template>
    <el-form :model="UpdateressForm">
      <el-form-item label="省" prop="province">
        <el-input
            v-model="UpdateressForm.province"
            clearable
            placeholder="省"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="市" prop="city">
        <el-input
            v-model="UpdateressForm.city"
            clearable
            placeholder="市"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="区" prop="district">
        <el-input
            v-model="UpdateressForm.district"
            clearable
            placeholder="县、区"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮政编码" prop="zip">
        <el-input
            v-model="UpdateressForm.zip"
            clearable
            placeholder="邮政编码"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input
            v-model="UpdateressForm.address"
            clearable
            placeholder="详细地址"
            size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="类型">
        <el-radio-group v-model="UpdateressForm.isDefault">
          <el-radio label="1">默认</el-radio>
          <el-radio label="0">不默认</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button color="red" type="primary" @click="Updatesubmit">确认</el-button>
        <el-button @click="Updateclose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>


<script setup lang="ts" name="userDetails">
import {useRouter,useRoute} from "vue-router";
import { UserFilled ,ArrowLeftBold,LocationFilled,Key,PictureFilled,Edit,Finished} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from "vue";
import { reqUpdatePasswordUser, reqUpdateUser, reqUserInfo} from "@/api/user";
import {ResponseData} from "@/api/user/type";
import {ElMessage} from "element-plus";
import type { UploadProps } from 'element-plus'
import useUserStore from "@/store/modules/user";
import {reqAddUserAdress, reqDelateUserAdress, reqUpdateUserAdress, reqUserAdressList} from "@/api/adress";
let UserStore = useUserStore()
const editFlag = ref(false);
const router = useRouter();
const route =  useRoute();
const userId =ref(route.query.row);
const userInfo =ref([]);
const userAdressList =ref([]);
const flag = route.query.flag;
const oldPassword = ref("");
const newPassword = ref("");
const goBack = () => {
  router.back();
};
const onEdit =(()=>{
  if(editFlag.value) {
    editFlag.value = !editFlag.value;
  }else {
    editFlag.value = !editFlag.value;
  }
})
const onFinished = ( async () => {
  if(editFlag.value ){
  let userUpdateRequestData = {
    "id": userInfo.value.id,
    "userId": userInfo.value.userId,
    "userLevel": userInfo.value.userLevel,
    "userName": userInfo.value.userName,
    "realName": userInfo.value.realName,
    "gender": userInfo.value.gender,
    "identityCardType": userInfo.value.identityCardType,
    "userProfile": userInfo.value.userProfile,
    "email": userInfo.value.email,
    "phone": userInfo.value.phone,
    "userMoney": userInfo.value.userMoney,
    "userPoint": userInfo.value.userPoint,
    "userStats": userInfo.value.userStats,
    "userType": userInfo.value.userType
  };
  let res = await reqUpdateUser(userUpdateRequestData);
  if(res.data == true){
    editFlag.value = !editFlag.value;
    ElMessage.success("更改成功");
  }else {
    editFlag.value = !editFlag.value;
    ElMessage.error("更改失败");
  }
  }
})
const init = ( async ()=>{
  let res: ResponseData = await reqUserInfo(userId.value)
  userInfo.value = res.data;
  if(flag == "user") {
    UserStore.userName = res.data.userName as string
    UserStore.userAvatar = res.data.userAvatar as string
  }
  let userAddress: ResponseData = await reqUserAdressList({id :userId.value})
  if(userAddress.data.records){
    userAdressList.value = userAddress.data.records;
  }else{
    ElMessage.error("地址请求数据为空...");
  }
})

const AddIsShowDialog = ref(false);
const AddressForm = reactive({
  userId: userId.value,
  province: "",
  city:"",
  district:"",
  address:"",
  isDefault:0,
  zip:"",
});
const UpdateressForm = reactive({
  id:"",
  userId: userId.value,
  province: "",
  city:"",
  district:"",
  address:"",
  isDefault:0,
  zip:"",
});
const addAddressDialog = ((item : any)=>{
  AddressForm.province = "";
  AddressForm.city = "";
  AddressForm.district = "";
  AddressForm.address = "";
  AddressForm.isDefault = "";
  AddressForm.zip = "";
  AddIsShowDialog.value = true;
})
const UpdateIsShowDialog = ref(false);
const UpdateAddressDialog = ((item : any)=>{
  UpdateressForm.id = item.id;
  UpdateressForm.province = item.province;
  UpdateressForm.city = item.city;
  UpdateressForm.district = item.district;
  UpdateressForm.address = item.address;
  UpdateressForm.isDefault = item.isDefault;
  UpdateressForm.zip = item.zip;
  UpdateIsShowDialog.value = true;
})
const Addsubmit = ( async () =>{

  var res = await reqAddUserAdress(AddressForm);
  if (res.code === 0) {
    AddIsShowDialog.value = false;
    ElMessage.success("新增成功");
    init();
  } else {
    //提示信息添加失败
    ElMessage.error(res.message);
  }
})
const Updatesubmit = ( async () =>{
  var res = await reqUpdateUserAdress(UpdateressForm);
  if (res.code === 0) {
    UpdateIsShowDialog.value = false;
    ElMessage.success("修改成功");
    init();
  } else {
    //提示信息修改失败
    ElMessage.error(res.message);
  }
})
const Addclose = () => {
  AddIsShowDialog.value = false;
}
const Updateclose = () => {
  UpdateIsShowDialog.value = false;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpg'||rawFile.type == 'image/jpeg'||rawFile.type == 'image/svg'||rawFile.type == 'image/png'||rawFile.type == 'image/webp')) {
    ElMessage.error('头像图片必须是（jpg/jpeg/svg/png/webp）中任意的格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过2MB!')
    return false
  }
  return true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = () => {
  ElMessage.success('上传成功!')
  init();
}
const updatePassword = ( async ()=>{
  let userUpdatePasswordRequestData = {
    id:userId.value,
    oldPassword:oldPassword.value,
    newPassword:newPassword.value
  }
  var res :  ResponseData = await reqUpdatePasswordUser(userUpdatePasswordRequestData);
  if(res.data == true){
    if(flag == "user"){
      oldPassword.value = "";
      newPassword.value = "";
      await UserStore.userLogout()
      router.push({ path: '/login', query: { redirect: route.path } })
      ElMessage.success("修改成功,请重新登录");
    }else {
      oldPassword.value = "";
      newPassword.value = "";
      ElMessage.success("已成功修改此用户的密码");
    }
  }else {
    ElMessage.error(res.message);
  }
})
const removeAdressDialog =( async (item : any)=>{
  let id = item.id
    var res =  await reqDelateUserAdress({id:id});
  if(res.code == 0){
    ElMessage.success("删除成功");
    init();
  }else {
    ElMessage.error(res.message);
  }
})
onMounted(() => {
  init();
})
</script>


<style scoped>
.page-header{
  background: #f8f6f6;
  height: 30px;
}
.all-search {
  padding-top: 5px;
  display: flex;
  justify-content: flex-end;
}
.avatar {
  margin-left: 30px;
  margin-top: 15px;
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 50%;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  width: 100%;
}
.search-form .el-form-item {
  width: calc(100% / 3);
  padding-right: 20px;
  padding-top: 10px;
  box-sizing: border-box;
}
.search-form .el-form-item:last-child {
  width: 60%; /* 最后一个任务单状态独占一行 */
}
.all-add {
  margin-bottom: 10px;
  display: flex;
}
.btn-background-color-add {
  background-color: #148f34;
  color: white;
}
.btn-background-color-red {
  background-color: #f80317;
  color: white;
  height: 22px;
  float: left;
}
.btn-background-color-xiangqing {
  background-color: #afa681;
  color: white;
  height: 22px;
  float: left;
}
</style>